package com.family.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.family.domain.Authority;
import com.family.domain.Authority_role;
import com.family.domain.Role;
import com.family.domain.User;
import com.family.inter.IAuthority;
import com.family.inter.IAuthority_role;
import com.family.inter.IRole;
import com.family.inter.IUser;
import com.family.jsontmp.tree;


@Controller
public class UserAction {
    private static Logger logger = Logger.getLogger(UserAction.class);

    @Resource
    IUser iuser;

    @Resource
    IAuthority iautnority;

    @Resource
    IRole irole;

    @Resource
    IAuthority_role iautrole;

    @ResponseBody
    @RequestMapping("/add_AuthorityList")
    public String addAuthorityList(String id,String authorityList,ModelMap model)
    {
        //System.out.println(id+" "+authorityList);
        iautrole.delByRoleid(id);

        String[] list = authorityList.split(",");

        Authority_role obj = new Authority_role();
        for(int i=0;i<list.length;i++)
        {

            obj.setRole_id(id);
            obj.setAuthority_id(list[i]);
            iautrole.addAuthority_role(obj);

        }

        return "success";
    }


    @ResponseBody
    @RequestMapping("/add_authority_role")
    public String addAuthority_role(String strAt,HttpServletResponse response)
    {
        String[] arr = strAt.split(",");
        return "success";
    }




    @ResponseBody
    @RequestMapping("/add_user")
    public String UserAdd(User user,HttpServletResponse response)
    {
        UUID uuid = UUID.randomUUID();
        user.setId(uuid.toString());
        iuser.addUser(user);

        return "success";
    }

    @ResponseBody
    @RequestMapping("/updatePwd")
    public String updatePwd(String userid,String orpwd,String nepwd)
    {

        Map<String, String> map = new HashMap<String, String>();
        map.put("login_id", userid);
        map.put("login_pwd", orpwd);
        map.put("nepwd", nepwd);

        User user = iuser.user_login(map);

        if(user==null)
        {
            return "error";
        }
        else
        {
            iuser.updatePwd(map);
        }

        return "success";
    }

    @ResponseBody
    @RequestMapping("/add_role")
    public String UserRole(Role role,HttpServletResponse response)
    {
        UUID uuid = UUID.randomUUID();
        role.setId(uuid.toString());

        irole.addRole(role);

        return uuid.toString();
    }

    @ResponseBody
    @RequestMapping("/delete_user")
    public String DelUser(String id,HttpServletResponse response)
    {
        iuser.delete(id);
        return "success";
    }

    @ResponseBody
    @RequestMapping("/delete_role")
    public String DelRole(String id,HttpServletResponse response)
    {
        irole.delByid(id);
        iautrole.delByRoleid(id);
        return "success";
    }







    @ResponseBody
    @RequestMapping("/loadMenuTree")
    public void loadMenuTree(String role_id,ModelMap model,HttpSession session,HttpServletResponse response)
    {

        User user = (User) session.getAttribute("user");

        List<Authority> arrList = iautrole.selectAutListByRoleId(user.getRole_id());

        ArrayList<tree> arr = new ArrayList<tree>();
        tree root = new  tree();

        showMenu("root",root,arrList);

        //System.out.println("load tree");

        arr.add(root);

//		return root;

        String jsonArray = JSONArray.toJSONString(arr);
        //System.out.println(jsonArray);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print(jsonArray);
        out.close();
    }

    @ResponseBody
    @RequestMapping("/loadTree")
    public void show_add_Authority(String role_id,ModelMap model,HttpServletResponse response)
    {
        ArrayList<tree> arr = new ArrayList<tree>();
        tree root = new  tree();

        //System.out.println(role_id);


        List<Authority> arrList = iautrole.selectAutListByRoleId(role_id);

        showAuthority("root",root,arrList);

        arr.add(root);

        String jsonArray = JSONArray.toJSONString(arr);

        //System.out.println(jsonArray);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print(jsonArray);
        out.close();
    }



    @ResponseBody
    @RequestMapping("/user_login")
    public String  UserLogin(String login_id,String login_pwd,HttpServletRequest request)
    {

        Map<String, String> map = new HashMap<String, String>();

        map.put("login_id", login_id);
        map.put("login_pwd", login_pwd);

        User user = iuser.user_login(map);

        if(user==null)
        {
            logger.info("登陆失败"+login_id);
            //System.out.println("登陆失败");
            return "error";
        }else
        {
            logger.info("登陆成功"+user.getLogin_name());
            request.getSession().setAttribute("user",user);

            UUID uuid = UUID.randomUUID();
            user.setId(uuid.toString());


            Application.key=uuid.toString();

            return "success"+"|"+uuid.toString();
        }

    }

    @ResponseBody
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request)
    {
        HttpSession session = (HttpSession)request.getSession();
        session.invalidate();

        return "index";
    }

    public void showAuthority(String parent_id,tree tree,List<Authority> arrRole)
    {
        List<Authority> arr = iautnority.getAuthorityList(parent_id);
        if(arr.size()>0)
        {
            Authority root = iautnority.getAuthorityById(parent_id);
            List<tree> child = new ArrayList<tree>();

            tree.setId(root.getId());
            tree.setText(root.getA_name());

            for(Authority aut:arr)
            {
                tree t = new tree();
                showAuthority(aut.getId(),t,arrRole);
                child.add(t);
            }
            tree.setChildren(child);

        }else
        {
            Authority aut = iautnority.getAuthorityById(parent_id);
            if(arrRole.contains(aut))
            {
                tree.setChecked(true);
            }

            tree.setId(aut.getId());
            tree.setText(aut.getA_name());
        }

    }

    public void showMenu(String parent_id,tree tree,List<Authority> arrRole)
    {
        List<Authority> arr = iautnority.getAuthorityList(parent_id);
        if(arr.size()>0)
        {
            Authority root = iautnority.getAuthorityById(parent_id);
            List<tree> child = new ArrayList<tree>();

            tree.setId(root.getA_url());
            tree.setText(root.getA_name());

            for(Authority aut:arr)
            {
                tree t = new tree();
                showMenu(aut.getId(),t,arrRole);
                //System.out.println("list="+t.getText());
                if(t.getId()!=null)
                {
                    child.add(t);
                }else if(aut.getA_url()==null)
                {
                    if(t.getChildren()!=null)
                    {
                        child.add(t);
                    }

                }
                else
                {
                    //System.out.println("sub="+t.getText());
                }
            }
            if(child.size()>0)
                tree.setChildren(child);

        }
        else
        {
            Authority aut = iautnority.getAuthorityById(parent_id);

            if(arrRole.contains(aut)||aut.getA_url().trim().length()==0)
            {
                tree.setChecked(true);
                tree.setId(aut.getA_url());
                tree.setText(aut.getA_name());
                //System.out.println("not null="+aut.getA_name());
            }else
            {
                tree = null;
                //System.out.println("null="+aut.getA_name()+"url=["+aut.getA_url().length()+"]");
            }


        }

    }



}
